//  Created by zmyl on 2025/6/10.
//  Copyright © 2025 zmyl. All rights reserved.

#import "MBProgressHUD+Count.h"
#import <libkern/OSAtomic.h>
#import <stdatomic.h>
#import "IWindowProvider.h"
//#import "AppDelegate.h"
//#import "../AppDelegate.h"

static atomic_int _activityCount = 0; // 使用 atomic_int 替代 int32_t
static UIWindow *_injectWindow = nil;
//static UIWindow *_cachedWindow = nil;

@implementation MBProgressHUD (Count)

//+ (void)initialize {
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(handleWindowChange:)
//                                                 name:@"AppWindowDidChange"
//                                               object:nil];
//}
//
//+ (void)handleWindowChange:(NSNotification *)notification {
//    _cachedWindow = notification.object;
//}

+ (void)incrementActivityCount {
    dispatch_async(dispatch_get_main_queue(), ^{
        // 使用原子操作替代 OSAtomicIncrement32
        atomic_fetch_add_explicit(&_activityCount, 1, memory_order_relaxed);

        /// 检查是否需要显示 HUD
        if (atomic_load_explicit(&_activityCount, memory_order_relaxed) == 1) {
            UIWindow *targetWindow = [self findBestWindow];
            [MBProgressHUD showHUDAddedTo: targetWindow animated:YES];
        }
    });
}

+ (void)decrementActivityCount {
    dispatch_async(dispatch_get_main_queue(), ^{
        // 获取减少前的值用于日志
        int preCount = atomic_load_explicit(&_activityCount, memory_order_relaxed);
        // 使用原子操作减少计数
        atomic_fetch_sub_explicit(&_activityCount, 1, memory_order_relaxed);

        // 获取减少后的值
        int newCount = atomic_load_explicit(&_activityCount, memory_order_relaxed);
        NSLog(@"MBProgressHUD计数器减少: %d -> %d", preCount, newCount);

        // 处理计数器归零
        if (newCount <= 0) {
            atomic_store_explicit(&_activityCount, 0, memory_order_relaxed);
            UIWindow *targetWindow = [self findBestWindow];
            [MBProgressHUD hideHUDForView:targetWindow animated:YES];
        }
    });
}

+ (instancetype)sharedInstanceWithWindow:(UIWindow *)window {
    static MBProgressHUD *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [MBProgressHUD alloc];
        _injectWindow = window;
    });
    return sharedInstance;
}

// 找到最适合显示HUD的窗口(四级回退策略确保总能找到合适的窗口)
+ (UIWindow *)findBestWindow {
    if (_injectWindow) return _injectWindow;
    
    // 1. 优先使用应用委托指定的窗口
    // 通过协议获取窗口
    id<IWindowProvider> provider = (id<IWindowProvider>)[UIApplication sharedApplication].delegate;

    if ([provider respondsToSelector:@selector(mainWindow)]) {
        UIWindow *mainWindow = [provider mainWindow];
        if (mainWindow) return mainWindow;
    }
    
    UIWindow *keyWindow = nil;
    if (@available(iOS 13.0, *)) {
        for (UIWindowScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive) {
                // iOS 13-14 需遍历场景的 windows
                for (UIWindow *window in scene.windows) {
                    if (window.windowLevel == UIWindowLevelNormal && !window.hidden) {
                        keyWindow = window;
                        break;
                    }
                }
                if (keyWindow) break;
            }
        }
    } else {
        // iOS 12 兼容逻辑
//        keyWindow = [UIApplication sharedApplication].keyWindow;
    }
    if (keyWindow) return keyWindow;

    // 3. 使用最顶层的窗口
    NSArray *windows = [UIApplication sharedApplication].windows;
    for (UIWindow *window in windows.reverseObjectEnumerator) {
        if (window.windowLevel == UIWindowLevelNormal && !window.hidden) {
            return window;
        }
    }

    // 4. 最后尝试主窗口
    return [UIApplication sharedApplication].delegate.window;
}
@end
